package cording.example.addressList.Service.impl;

import cording.example.addressList.Service.ContactService;
import cording.example.addressList.mybatis.entity.Contact;
import cording.example.addressList.mybatis.mapper.ContactListMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ContactServiceImpl implements ContactService {
    @Autowired
    private ContactListMapper contactListMapper;
    @Override
    public List<Contact> findAllContacts() {
        return contactListMapper.findAll();
    }

    @Override
    public Contact findContactById(Long id) {
        return contactListMapper.findById(id).orElse(null);
    }

    @Override
    public void deleteContact(Long id) {
        contactListMapper.deleteById(id);
    }

    @Override
    public void saveContact(Contact contact) {
        contactListMapper.save(contact);
    }
    @Override
    public void addContact(Contact contact){
        Contact existingContact = contactListMapper.findByPhoneNumber(contact.getPhoneNumber());
        if (existingContact != null) {
            throw new DuplicateKeyException("手机号已存在");
        }
        Contact existing1Contact = contactListMapper.findByEmail(contact.getEmail());

        if (existing1Contact != null) {
            throw new DuplicateKeyException("手机号已存在");
        }
        contactListMapper.add(contact);
    }
    @Override
    public List<Contact> findByName(String name) {
        return contactListMapper.findByNameContaining(name);
    }
    @Override

    public List<Contact> findByPhoneNumber(String phoneNumber) {
        return contactListMapper.findByPhoneNumberContaining(phoneNumber);
    }
    @Override

    public List<Contact> getAllContacts() {
        return contactListMapper.findAll();
    }

}
